/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package io.iec.edp.caf.autoconfigure;

import com.ulisesbocchio.jasyptspringboot.annotation.EnableEncryptableProperties;
import io.iec.edp.caf.commons.utils.CapEncryptorConfigPostProcessor;
import io.iec.edp.caf.commons.utils.CapLazyEncryptor;
import io.iec.edp.caf.commons.utils.CapPropertyPlaceholderConfigurer;
import io.iec.edp.caf.commons.utils.SpringBeanUtils;
import lombok.var;
import org.jasypt.encryption.pbe.PBEStringEncryptor;
import org.jasypt.encryption.pbe.PooledPBEStringEncryptor;
import org.jasypt.encryption.pbe.config.SimpleStringPBEConfig;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.Environment;
import org.springframework.core.io.FileSystemResource;

import java.nio.file.Paths;
import java.util.Objects;
import java.util.Properties;

/**
 * @author wangyandong
 * @date 2019/9/20 16:36
 * @email wangyandong@inspur.com
 */
@Configuration(proxyBeanMethods = false)
@EnableEncryptableProperties
public class CAFUtilsAutoConfiguration implements EnvironmentAware, BeanFactoryAware, ApplicationContextAware {
    private Environment environment;

    private BeanFactory beanFactory;


    /**
     * 加载外部配置文件
     *
     * @return
     */
    @Bean
    @Primary
    public CapPropertyPlaceholderConfigurer propertyConfigurer() {
        CapPropertyPlaceholderConfigurer configurer = new CapPropertyPlaceholderConfigurer();
        YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
        //此处替换为自身项目安全敏感信息存放目录即可 暂定为项目运行时根目录
        try {
            yaml.setResources(new FileSystemResource(Paths.get(getRuntimePath(), "config.yaml").toFile()));
            Properties props = new Properties();
            props.putAll(Objects.requireNonNull(yaml.getObject()));
            configurer.setProperties(props);
        } catch (Exception e) {
            return configurer;
        }

        return configurer;
    }

    /**
     * 将配置加密工具注册为bean
     * 用户使用时需要在application.yaml里指定jasypt.encryptor.bean节点值为cafConfigEncryptor
     * <p>
     * 此处Lazy Tag保证用户如果不需要加密 可以不填写jasypt.encryptor.password节点
     *
     * @return
     */
    @Bean(name = "cafConfigEncryptor")
    public PBEStringEncryptor capStringEncryptor(@Qualifier("capEncryptorConfig") SimpleStringPBEConfig config) {
        PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor();
        encryptor.setConfig(config);
        return encryptor;
}

//    @Lazy()
//    public PBEStringEncryptor capStringEncryptor() {
//        return CapLazyEncryptor.getSingleton(environment, beanFactory);
//    }

    /**
     * 配置读取processor
     *
     * @param environment
     * @return
     */
    @Bean
    public CapEncryptorConfigPostProcessor capEncryptorConfigPostProcessor(ConfigurableEnvironment environment) {
        return new CapEncryptorConfigPostProcessor(environment);
    }


    /**
     * 实现ApplicationContextAware接口的回调方法。设置上下文环境
     *
     * @param applicationContext
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        SpringBeanUtils.setApplicationContext(applicationContext);
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.beanFactory = beanFactory;
    }

    @Override
    public void setEnvironment(Environment environment) {
        this.environment = environment;
    }

    public String getRuntimePath() {
        ApplicationHome home = new ApplicationHome(deduceMainApplicationClass());
        // returns the folder where the jar is. This is what I wanted.
        String path = home.getDir().getAbsolutePath().replaceAll("\\\\", "/");
        // Remove leading /.
        if (System.getProperty("os.name").toLowerCase().contains("linux")) {
            return path;
        }

        return path.replaceFirst("^/", "");
    }

    Class<?> deduceMainApplicationClass() {
        try {
            StackTraceElement[] stackTrace = new RuntimeException().getStackTrace();
            for (StackTraceElement stackTraceElement : stackTrace) {
                if ("main".equals(stackTraceElement.getMethodName())) {
                    return Class.forName(stackTraceElement.getClassName());
                }
            }
        } catch (ClassNotFoundException ex) {
            // Swallow and continue
        }
        return null;
    }
}
